package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping("/loginUser")
    public Object loginUser(User user, Model model, HttpSession session){
        Object o = userService.login(user).get("user");
        if (o != null) {
            session.setAttribute("loginUser",o);
            model.addAttribute("user",o);
            return "showUser.jsp";
        }
        model.addAttribute("msg",userService.login(user).get("msg"));
        return "login.jsp";
    }

    @RequestMapping("/registers")
    public Object addUser(@Valid User user, BindingResult bindingResult, Model model, @RequestParam(required = true,name = "userHead") MultipartFile multipartFile){
        Map<String,String> map = new HashMap<>();
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
            for (FieldError error : errors) {
                map.put(error.getField(), error.getDefaultMessage());
            }
            model.addAttribute("error", map);
            return "register.jsp";
            }
        //文件夹
        File folder = new File("C:\\headImg\\"+user.getUserName());
        //存入盘内路径
        String filePath = "";
        //存入数据库路径
        String headImg ="";
        if (!multipartFile.isEmpty()) {
            filePath = "C:\\headImg\\"+user.getUserName()+"\\"+multipartFile.getOriginalFilename();
            headImg = "/SpringMVC_03/headImg/"+user.getUserName()+"\\"+multipartFile.getOriginalFilename();
        }

        File file = new File(filePath);

        if (multipartFile.getSize() < 1024*1024*10) {
            user.setHeadImg(headImg);
            int row = userService.register(user);
            if (row == 1) {
                model.addAttribute("msg", "注册成功");
                model.addAttribute("user", user);
                try {
                    if (!"".equals(filePath)) {
                        create(folder,file,multipartFile);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "login.jsp";
            } else if(row == -1){
                model.addAttribute("msg", "账号存在");
                return "register.jsp";
            }
            model.addAttribute("msg","注册失败，未知原因，联系管理员");
        }
        return "register.jsp";
    }

    //创建文件夹和文件
    private boolean create(File folder,File file,MultipartFile multipartFile) throws IOException {
        if (!folder.exists()) {
            if(folder.mkdirs()){
                multipartFile.transferTo(file);
                return true;
            } else {
                return false;
            }
        } else {
            multipartFile.transferTo(file);
            return true;
        }
    }
}
